package me.guowenlong.transformer.compoment;

import org.reactivestreams.Publisher;

import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.functions.Function;
import me.guowenlong.transformer.bean.RetryBean;

/**
 * desc   : Flowable的重试Function
 * author : guowenlong
 * Email  : guowenlong20000@gmail.com
 * time   : 2019年01月02日16 : 01
 */
public class FlowRetryFunction extends AbsRetryFunction implements Function<Flowable<Throwable>, Publisher<?>> {

    public FlowRetryFunction(Function<Throwable, RetryBean> retryWhen) {
        this.retryConfigProvider = retryWhen;
    }

    @Override
    public Publisher apply(Flowable<Throwable> throwableFlowable) throws Exception {
        return throwableFlowable.flatMap(error -> {
            RetryBean retryConfig = retryConfigProvider.apply(error);
            if (++retryCount <= retryConfig.getMaxRetries()) {
                return retryConfig.getCondition().flatMapPublisher(retry -> {
                    if (retry) {
                        return Flowable.timer((long) retryConfig.getRetryDelay(), TimeUnit.MILLISECONDS);
                    } else {
                        return Flowable.error(error);
                    }
                });
            } else {
                return Flowable.error(error);
            }
        });
    }
}